// app/api/files/[...path]/route.ts import { NextRequest, NextResponse } from 'next/server' import { readFile } from 'fs/promises' import { join } from 'path' import { stat } from 'fs/promises' export async function GET( request: NextRequest, { params }: { params: { path: string[] } } ) { try { const path = request.nextUrl.searchParams.get("path"); // 경로 파라미터에서 파일 경로 조합 const filePath = join(process.cwd(), 'uploads', ...params.path) // 파일 존재 여부 확인 try { await stat(filePath) } catch (error) { return NextResponse.json( { error: 'File not found' }, { status: 404 } ) } // 파일 읽기 const fileBuffer = await readFile(filePath) // 파일 확장자에 따른 MIME 타입 설정 const fileName = params.path[params.path.length - 1] const fileExtension = fileName.split('.').pop()?.toLowerCase() let contentType = 'application/octet-stream' if (fileExtension) { const mimeTypes: Record = { 'pdf': 'application/pdf', 'doc': 'application/msword', 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'xls': 'application/vnd.ms-excel', 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'ppt': 'application/vnd.ms-powerpoint', 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'txt': 'text/plain', 'csv': 'text/csv', 'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'gif': 'image/gif', } contentType = mimeTypes[fileExtension] || contentType } // 다운로드 설정 const headers = new Headers() headers.set('Content-Type', contentType) headers.set('Content-Disposition', `attachment; filename="${fileName}"`) return new NextResponse(fileBuffer, { status: 200, headers, }) } catch (error) { console.error('Error downloading file:', error) return NextResponse.json( { error: 'Failed to download file' }, { status: 500 } ) } }